package com.hawk.eye.common.encipher;

import com.hawk.eye.common.config.HawkEyeEncipherProperties;
import com.hawk.eye.common.model.ServiceMetadata;
import com.hawk.eye.common.utils.AesUtil;
import com.hawk.eye.common.utils.JsonUtil;
import lombok.AllArgsConstructor;

import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * @className: MessageEncipher
 * @description:
 * @author: salad
 * @date: 2023/12/24
 **/
@AllArgsConstructor
public class MessageEncipher {

    private final HawkEyeEncipherProperties properties;

    private final ISecureProcessor secureProcessor;

    public boolean enabled() {
        return properties.isEnabled();
    }

    public <T> T decrypt(String value, Class<T> type) {
        byte[] decrypt = secureProcessor.decrypt(parseHexStr2Byte(value), properties.getSecureKey());
        if (String.class.isAssignableFrom(type)) {
            return (T) new String(decrypt, StandardCharsets.UTF_8);
        } else {
            return JsonUtil.parse(decrypt, type);
        }
    }

    public String encrypt(Object value) {
        return parseByte2HexStr(secureProcessor.encrypt(value, properties.getSecureKey()));
    }

    /**
     * 将二进制转换成16进制
     *
     * @param buf
     * @return
     */
    public String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     *
     * @param hexStr
     * @return
     */
    public byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
